﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Pixysoft.Framework.Sockets.Controller
{
    class ThreadPoolController
    {
        /// <summary>
        /// 注册一个一次调用的对象
        /// </summary>
        /// <param name="callable"></param>
        /// <param name="state"></param>
        public static void Queue(IThreadPoolCallable callable, object state)
        {
            if (!callable.IsRunning)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(callable.Call), state);
            }
        }

        /// <summary>
        /// 注册轮训 每interval秒触发一次 不受处理时间影响一定触发
        /// </summary>
        /// <param name="runnable"></param>
        /// <param name="state"></param>
        /// <param name="interval"></param>
        /// <param name="onlyOnce"></param>
        public static void Register(IThreadPoolRunnable runnable, object state, long interval, bool onlyOnce)
        {
            LoggerHelper.Debug("begin register runnable target:{0}", runnable.ToString());

            runnable.WaitHandler = new AutoResetEvent(false);

            runnable.RegisterdHandler = ThreadPool.RegisterWaitForSingleObject(
                runnable.WaitHandler, new WaitOrTimerCallback(runnable.Run), state, interval, onlyOnce);

            runnable.IsRunning = true;
        }

        /// <summary>
        /// 注销轮循线程
        /// </summary>
        /// <param name="runnable"></param>
        public static void Unregister(IThreadPoolRunnable runnable)
        {
            if (runnable.RegisterdHandler != null && runnable.WaitHandler != null)
            {
                LoggerHelper.Debug("begin Unregister runnable target:{0}", runnable.ToString());

                runnable.RegisterdHandler.Unregister(runnable.WaitHandler);
            }

            runnable.IsRunning = false;
        }
    }

    interface IThreadPoolCallable
    {
        /// <summary>
        /// 是否正在执行
        /// </summary>
        bool IsRunning { get;}

        void Call(object state);
    }

    interface IThreadPoolRunnable : IDisposable
    {
        /// <summary>
        /// 是否正在执行
        /// </summary>
        bool IsRunning { get;set;}

        /// <summary>
        /// 是否已经处理
        /// </summary>
        bool IsDisposed { get;}

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="state"></param>
        /// <param name="timeOut"></param>
        void Run(object state, bool timeOut);

        /// <summary>
        /// 注册在线程池后的信号变量
        /// </summary>
        /// <value></value>
        WaitHandle WaitHandler { get; set; }

        /// <summary>
        /// 注册后的对象
        /// </summary>
        /// <value></value>
        RegisteredWaitHandle RegisterdHandler { get; set; }
    }
}
